package tools

import (
	"errors"
	"io"
	"net/http"
	"net/url"
	"reflect"
	"time"
)

var (
	httpClient = &http.Client{Timeout: 5 * time.Second}
)

func DoHttp(url, method string, headers map[string]string, postParams io.Reader, getParams url.Values) (res []byte, err error) {
	var (
		req *http.Request
	)
	if method == "GET" {
		if postParams != nil {
			err = errors.New("GET传参异常! 请检查")
			return
		}
		if getParams != nil {
			url += "?" + getParams.Encode()
		}
		req, err = http.NewRequest(method, url, nil)
	} else {
		if getParams != nil {
			err = errors.New("非GET传参异常! 请检查")
			return
		}
		req, err = http.NewRequest(method, url, postParams)
	}
	if err != nil {
		return
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0")
	if len(headers) > 0 {
		for key, value := range headers {
			req.Header.Set(key, value)
		}
	}

	resp, err := httpClient.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	res, err = io.ReadAll(resp.Body)
	return
}

func StructToMap(obj any) map[string]any {
	result := make(map[string]any)
	v := reflect.ValueOf(obj)
	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}
	if v.Kind() != reflect.Struct {
		return nil
	}
	t := v.Type()
	for i := 0; i < v.NumField(); i++ {
		field := v.Field(i)
		var val any
		if field.Kind() == reflect.Ptr {
			if !field.IsNil() {
				val = field.Elem().Interface()
			}
		} else {
			val = field.Interface()
		}
		if val != nil {
			result[t.Field(i).Tag.Get("json")] = val
		}
	}
	return result
}
